import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

// 路由配置数组
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: {
      title: '登录页面',
      requiresAuth: false
    }
  },
  {
    // 首页路由，这里暂时使用一个简单的组件
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: {
      title: '首页',
      requiresAuth: true
    }
  },
  {
    path: '/upload-download',
    name: 'UploadDownload',
    component: () => import('../views/UploadDownload.vue'),
    meta: {
      title: '断点续传上传下载',
      requiresAuth: true
    }
  },
  {
    // 捕获所有未匹配的路由，重定向到登录页
    path: '/:pathMatch(.*)*',
    redirect: '/login'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 })
})

// 全局前置守卫
router.beforeEach((to, _from, next) => {
  // 设置页面标题
  document.title = to.meta.title as string || '体育应用'
  
  // 检查是否需要登录
  const requiresAuth = to.meta.requiresAuth
  
  // 从localStorage获取token
  const token = localStorage.getItem('token')
  
  // 如果需要登录但没有token，则重定向到登录页
  if (requiresAuth && !token) {
    next('/login')
  } else {
    // 其他情况正常跳转
    next()
  }
})

export default router
